package com.cll.learn.rabbitmq.listener;

import com.cll.learn.rabbitmq.mapper.OrderMapper;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 描述信息:
 * 支付超时的消息监听器
 * @author CLL
 * @version 1.0
 * @date 2021/2/28 19:19
 */
@Component
public class RabbitMQTimeoutListener implements ChannelAwareMessageListener {

    private static final Logger logger = LoggerFactory.getLogger(RabbitMQTimeoutListener.class);

    @Autowired
    OrderMapper orderMapper;
    /**
     * 这里只监听支付超时进入到死信队列的消息
     * 接收到死信队列中的订单ID之后，进行数据库持久化操作
     * 如果订单未支付，就修改为已取消。如果订单已支付，不进行修改
     * @param message 消息信息
     * @param channel   连接信道
     * @throws Exception    异常信息
     */
    @RabbitListener(queues = "queue.order.dlx", ackMode = "MANUAL")
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String orderId = new String(message.getBody());
        orderId = orderId.replaceAll("\"","");
        logger.info("===>>> 订单ID = {}超时取消.length = {}", orderId, orderId.length());
        int i = orderMapper.updateState(orderId, 2, new Date(), 0);
        if (1 == i) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            logger.error("****** 从死信队列超时取消订单ID失败");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}